package net.j4love.grpc.demo.service;

import io.grpc.stub.StreamObserver;

/**
 * @author He Peng
 * @create 2018-05-13 15:11
 * @update 2018-05-13 15:11
 * @updatedesc : 更新说明
 * @see
 */
public class GreeterServiceImpl
        extends GreeterServiceGrpc.GreeterServiceImplBase {

    private void log() {
        System.out.println("gRPC Server Received Client Request");
    }


    @Override
    public void sayHello(GreeterServiceWrapper.HelloRequest request,
                         StreamObserver<GreeterServiceWrapper.HelloReply> responseObserver) {
        log();
        GreeterServiceWrapper.HelloReply helloReplyResponse =
                GreeterServiceWrapper.HelloReply
                .newBuilder()
                .setMessage("Hello , " + request.getName())
                .build();
        responseObserver.onNext(helloReplyResponse);
        responseObserver.onCompleted();
    }

    @Override
    public void lotsOfReplies(GreeterServiceWrapper.HelloRequest request, StreamObserver<GreeterServiceWrapper.HelloReply> responseObserver) {
        log();
        for (int i = 0 ; i < 3 ; i++) {
            GreeterServiceWrapper.HelloReply helloReplyResponse =
                    GreeterServiceWrapper.HelloReply
                            .newBuilder()
                            .setMessage(i + " -> Hello , " + request.getName())
                            .build();
            responseObserver.onNext(helloReplyResponse);
        }
        responseObserver.onCompleted();
    }

    @Override
    public StreamObserver<GreeterServiceWrapper.HelloRequest> lotsOfGreetings(StreamObserver<GreeterServiceWrapper.HelloReply> responseObserver) {
        log();
        return new StreamObserver<GreeterServiceWrapper.HelloRequest>() {
            @Override
            public void onNext(GreeterServiceWrapper.HelloRequest helloRequest) {
                GreeterServiceWrapper.HelloReply helloReplyResponse =
                        GreeterServiceWrapper.HelloReply
                                .newBuilder()
                                .setMessage("Hello , " + helloRequest.getName())
                                .build();
                responseObserver.onNext(helloReplyResponse);
            }

            @Override
            public void onError(Throwable throwable) {
                System.out.println("Error : " + throwable);
                responseObserver.onError(throwable);
            }

            @Override
            public void onCompleted() {
                System.out.println("Request Completed");
                responseObserver.onCompleted();
            }
        };
    }

    @Override
    public StreamObserver<GreeterServiceWrapper.HelloRequest> bidiHello(StreamObserver<GreeterServiceWrapper.HelloReply> responseObserver) {
        return super.bidiHello(responseObserver);
    }

}
